<template>
	<u-form-item :label="currentOptions.label" :prop="propName" :required="currentOptions.isRequired">
		<!-- 普通输入框 -->
		<template v-if="formItemType == 1">
			<u-input
				v-model="currentValue"
				:placeholder="currentOptions.placeholder"
				:maxlength="currentOptions.maxlength"
				:minlength="currentOptions.minlength"
				:disabled="formDisable || !currentOptions.isEnable"
				:custom-style="{ color: formDisable || !currentOptions.isEnable ? '#8799a3' : '#303133' }"
				input-align="right"
				:clearable="false"
			/>
		</template>
		<!-- 文本域 -->
		<template v-else-if="formItemType == 2">
			<u-input
				v-model="currentValue"
				type="textarea"
				:placeholder="currentOptions.placeholder"
				:maxlength="currentOptions.maxlength"
				:minlength="currentOptions.minlength"
				:disabled="formDisable || !currentOptions.isEnable"
				:custom-style="{ color: formDisable || !currentOptions.isEnable ? '#8799a3' : '#303133' }"
				:auto-height="true"
				input-align="right"
				:clearable="false"
			/>
		</template>
		<!-- 日期时间选择 -->
		<template v-else-if="formItemType == 12 || formItemType == 3 || formItemType == 4">
			<u-input
				v-model="currentValue"
				:disabled="formDisable || !currentOptions.isEnable"
				:custom-style="{ color: formDisable || !currentOptions.isEnable ? '#8799a3' : '#303133' }"
				input-align="right"
				:clearable="false"
				type="select"
				@click="openTimeSelect"
			/>
			<u-picker mode="time" v-model="datePickerShow" :params="currentOptions.dateParams" @confirm="dateTimePickerChange"></u-picker>
		</template>
		<!-- 数字 -->
		<template v-else-if="formItemType == 5">
			<u-input
				v-model="currentValue"
				type="number"
				:placeholder="currentOptions.placeholder"
				:maxlength="currentOptions.maxlength"
				:minlength="currentOptions.minlength"
				:disabled="formDisable || !currentOptions.isEnable"
				:custom-style="{ color: formDisable || !currentOptions.isEnable ? '#8799a3' : '#303133' }"
				input-align="right"
				:clearable="false"
			/>
		</template>
		<!-- 下拉框 -->
		<template v-else-if="formItemType == 6 && currentOptions.cascader.length == 0">
			<template v-if="currentOptions.selectOption.length < 30">
				<u-input
					v-model="selectValueShow.name"
					:custom-style="{ color: formDisable || !currentOptions.isEnable ? '#8799a3' : '#303133' }"
					input-align="right"
					:clearable="false"
					type="select"
					:disabled="formDisable || !currentOptions.isEnable"
					@click="openSelect"
				/>
				<u-select
					v-model="selectShow"
					:default-value="[selectValueShow.index]"
					:list="currentOptions.selectOption"
					label-name="Name"
					value-name="No"
					@confirm="handleSelectChange"
				></u-select>
			</template>
			<template v-else>
				<bjx-inputs
					:disabled="formDisable || !currentOptions.isEnable"
					:value="selectValueShow.name"
					itemKey="Name"
					@list="searchSelectChange"
					@select="searchSelect"
					@close="searchSelectClose"
				></bjx-inputs>
			</template>
		</template>
		<!-- 树形选择 -->
		<template v-else-if="formItemType == 6 && currentOptions.cascader.length > 0">
			<view></view>
		</template>
		<!-- 开关 -->
		<template v-else-if="formItemType == 7">
			<switch
				:class="currentValue ? 'checked' : ''"
				:checked="currentValue ? true : false"
				:disabled="formDisable || !currentOptions.isEnable"
				@change="handleInput"
			></switch>
		</template>
		<!-- 单选框 -->
		<template v-else-if="formItemType == 8">
			<u-radio-group style="text-align: right;" :disabled="formDisable || !currentOptions.isEnable" @change="watchInputChange" v-model="currentValue">
				<u-radio v-for="(item, index) in currentOptions.selectOption" :key="index" :name="item.No">{{ item.Name }}</u-radio>
			</u-radio-group>
		</template>
		<!-- 地区选择 -->
		<template v-else-if="formItemType == 9">
			<city-picker class="formCityPicker picker" :value="currentValue" :disabled="formDisable || !currentOptions.isEnable" @change="cityChange"></city-picker>
		</template>
		<!-- 多选 -->
		<template v-else-if="formItemType == 10">
			<checkbox-group class="block" @change="handleSelectChange">
				<label v-for="(item, index) in currentOptions.selectOption" :key="index">
					<checkbox
						:class="currentValue == item.No ? 'checked' : ''"
						:checked="currentValue == item.No ? true : false"
						:value="item.No"
						:disabled="formDisable || !currentOptions.isEnable"
					></checkbox>
					{{ item.Name }}
				</label>
			</checkbox-group>
		</template>
		<!-- 图片 -->
		<template v-else-if="formItemType == 11">
			<view class="formItemImgContainer">
				<view class="formItemImgItem" v-for="(item, index) in currentOptions.imgUrls" :key="index">
					<image class="formItemImg" :src="item" @click="imgPre(item, index)" />
				</view>
			</view>
		</template>
		<template v-else-if="formItemType == 13">
			<text>{{ imageSelectName }}</text>
		</template>
	</u-form-item>
</template>

<script>
import { buildTree, findIndex } from '@/utils/tools.js';
import areaList from '@/utils/areaList.js';
import CityPicker from '@/components/city-picker/city-picker.vue';
import BjxInputs from '@/components/bjx-inputs/bjx-inputs.vue';
import ProductImageSelect from '@/components/kxj-previewImage/kxj-previewImage.vue';
let asyncSelectedIndex = [];
export default {
	components: { CityPicker, BjxInputs, ProductImageSelect },
	props: {
		formItemType: {
			type: Number,
			default: 0
		},
		// eslint-disable-next-line
		value: {
			default: '',
			required: true
		},
		options: {
			type: Object,
			default: () => {
				return {};
			}
		},
		propName: {
			type: String,
			default: '',
			required: true
		},
		formDisable: {
			type: Boolean,
			default: false
		},
		multiOption: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			currentValue: this.value,
			cascadePicker: null,
			cascadeText: '',
			cityNameShow: '',
			showImageSelect: false,
			imageSelectName: '',
			imageSelectImgs: [],
			imageSelectDesc: [],
			inputTimer: null,
			valueTimer:null,
			datePickerShow: false,
			selectShow: false
		};
	},
	computed: {
		rules() {
			return this.isRequired ? [{ required: true, message: `请输入${this.label}`, trigger: 'blur' }] : [];
		},
		currentOptions() {
			let options = this.options;
			let cascader = [];
			if (options.selectOption && options.selectOption.length > 0 && options.selectOption[0].hasOwnProperty('ParentNo')) {
				cascader = buildTree(JSON.parse(JSON.stringify(options.selectOption)), 0);
				console.log('tree', cascader, this.value);
				let path = findIndex(cascader, this.value);
				console.log('path', path);
				let textArr = [];
				path.forEach((e, i) => {
					asyncSelectedIndex.push(e.index);
					textArr.push(e.Name);
				});
				this.cascadeText = `${textArr.join('/')}`;
			}
			let dateParams = {
				year: false,
				month: false,
				day: false,
				hour: false,
				minute: false,
				second: false
			};
			return {
				label: '',
				isRequired: false,
				extraRules: [],
				placeholder: options.isRequired && options.isEnable ? '请输入' : '',
				rows: 2,
				dateFormat: 'yyyy-MM-dd',
				timeFormat: 'HH:mm:SS',
				datePickerType: 'date',
				numberMin: -Infinity,
				numberMax: Infinity,
				precision: 0,
				step: 1,
				selectOption: [],
				maxlength: 200,
				minlength: 0,
				isEnable: true,
				tip: '',
				imgUrls: [],
				dateParams,
				...options,
				cascader
			};
		},
		selectValueShow() {
			let name = '';
			let index = 0;
			if (this.currentOptions.selectOption && this.currentOptions.selectOption.length > 0) {
				let value = this.value;
				let opts = this.currentOptions.selectOption;
				for (let i = 0; i < opts.length; i++) {
					if (opts[i].No == value) {
						name = opts[i].Name;
						index = i;
						break;
					}
				}
			}
			return {
				name,
				index
			};
		}
	},
	watch: {
		value: {
			immediate: true,
			handler(val) {
				this.setCurrentValue(val);
			}
		},
		currentValue(val) {
			if (this.value === val) {
				return;
			}
			if ([1, 2, 5].indexOf(this.formItemType) > -1) {
				if (this.inputTimer) {
					clearTimeout(this.inputTimer);
					this.inputTimer = setTimeout(() => {
						this.watchInputChange(val);
					}, 1000);
				} else {
					this.inputTimer = setTimeout(() => {
						this.watchInputChange(val);
					}, 1000);
				}
			}
		}
	},
	mounted() {
		if (this.formItemType == 13 && this.options.selectOption) {
			let urlArr = [];
			let textArr = [];
			this.options.selectOption.forEach(e => {
				urlArr.push(e.listPicUrl);
				textArr.push(e.name);
			});
			this.imageSelectDesc = textArr;
		}
	},
	methods: {
		showCascadePicker() {
			if (this.formDisable || !this.currentOptions.isEnable) {
			} else {
				this.cascadePicker.show();
			}
		},
		openTimeSelect() {
			if (this.formDisable || !this.currentOptions.isEnable) {
				return;
			}
			this.datePickerShow = true;
		},
		openSelect() {
			if (this.formDisable || !this.currentOptions.isEnable) {
				return;
			}
			this.selectShow = true;
		},
		setCurrentValue(value) {
			if (this.formItemType == 13) {
				for (let i = 0; i < this.currentOptions.selectOption.length; i++) {
					if (this.currentOptions.selectOption[i].id == value) {
						this.imageSelectName = this.currentOptions.selectOption[i].name;
					}
				}
			}
			if (value === this.currentValue) return;
			this.currentValue = `${value}`;
		},
		handleInput(value) {
			console.log('valueChange', value);
			this.$emit('value-change', { key: this.propName, value: value.detail.value });
		},
		watchInputChange(value) {
			console.log(value);
			this.$emit('value-change', { key: this.propName, value: value });
		},
		handleDateChange(value) {
			console.log('valueChange', value);
			this.$emit('value-change', { key: this.propName, value: value.detail.value });
		},
		handleSelectChange(e) {
			console.log('valueChange', e);
			this.$emit('value-change', { key: this.propName, value: e[0].value, name: e[0].label });
		},
		handleCascaderChange(value) {
			console.log(value);
			let v = value[value.length - 1];
			let name = '';
			for (let i = 0; i < this.currentOptions.selectOption.length; i++) {
				if (this.currentOptions.selectOption[i].No == v) {
					name = this.currentOptions.selectOption[i].Name;
					break;
				}
			}
			this.$emit('value-change', { key: this.propName, value: v, name });
		},
		cascadePickerSelect(selectedVal, selectedIndex, selectedText) {
			console.log('cascadePickerSelect', selectedVal, selectedIndex, selectedText);
			let v = selectedVal[selectedVal.length - 1];
			let name = selectedText[selectedText.length - 1];
			this.cascadeText = selectedText.join('/');
			this.$emit('value-change', { key: this.propName, value: v, name });
		},
		handleMulitSelect(value) {
			console.log('valueChange', value);
			let opts = this.multiOption;
			let name = [];
			for (let i = 0; i < opts.length; i++) {
				if (
					value.some(e => {
						return e == opts[i].No;
					})
				) {
					name.push(opts[i].Name);
				}
			}
			this.$emit('value-change', { key: this.propName, value, name });
		},
		asyncChangeHandle(i, newIndex) {
			asyncSelectedIndex[i] = newIndex;
			this.cascadePicker.setData(this.currentOptions.cascader, asyncSelectedIndex);
		},
		dateTimePickerChange(e) {
			console.log(e);
			let dateArr = [];
			let timeArr = [];
			let dateStr = '';
			let timeStr = '';
			if (e.year) dateArr.push(e.year);
			if (e.month) dateArr.push(e.month);
			if (e.day) dateArr.push(e.day);
			if (dateArr.length > 1) {
				dateStr = dateArr.join('-');
			}

			if (e.hour) timeArr.push(e.hour);
			if (e.minute) timeArr.push(e.minute);
			if (e.second) timeArr.push(e.second);
			if (timeArr.length > 1) {
				timeStr = timeArr.join(':');
			}
			this.$emit('value-change', { key: this.propName, value: `${dateStr} ${timeStr}` });
		},
		cityChange(value) {
			this.setCurrentValue(value.key);
			this.$emit('value-change', {
				key: this.propName,
				value: value.key[value.length - 1],
				cityArr: value.key,
				cityNameArr: value.label
			});
		},
		searchSelectChange(e) {
			console.log(e);
			let value = e.value;
			if (value) {
				let dataSource = this.currentOptions.selectOption;
				let arr = [];
				for (let i = 0; i < dataSource.length; i++) {
					if (dataSource[i].Name.indexOf(value) !== -1) {
						arr.push(dataSource[i]);
					}
				}
				e.callback(arr);
			} else {
				e.callback(this.currentOptions.selectOption);
			}
		},
		searchSelect(e) {
			console.log(e);
			this.$emit('value-change', { key: this.propName, value: e.No, name: e.Name });
		},
		searchSelectClose(e) {},
		inputBlur(e) {
			let value = e.detail.value;
			if (this.currentOptions.isRequired && !value) {
				uni.showModal({
					title: '提示',
					content: `请输入${this.currentOptions.label}`,
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
						}
					}
				});
			}
		},
		validateItem(rule, value, callback, isRequired) {
			console.log('validateItem', this.currentValue, isRequired);
			//校验交由container层处理
			this.$emit('validate-item', {
				callback,
				value: this.currentValue,
				isRequired: isRequired,
				propName: this.propName
			});
		},
		resetValidate() {},
		imgPre(item, index) {
			uni.previewImage({
				urls: this.currentOptions.imgUrls,
				current: index
			});
		}
	}
};
</script>

<style lang="less">
.cu-form-group {
	border-bottom: 1rpx solid #eee;
	.dateTimeFormItemDatePicker {
		flex: 3;
		&:after {
			display: none;
		}
	}
	.dateTimeFormItemTimePicker {
		&:after {
			display: none;
		}
	}
}
.formItemImgContainer {
	display: flex;
	flex-wrap: wrap;
	width: 60%;
	justify-content: flex-end;
	padding: 10rpx 0;
	min-height: 100rpx;
	.formItemImgItem {
		width: 120rpx;
		height: 120rpx;
		margin-right: 8rpx;
		.formItemImg {
			width: 100%;
			height: 100%;
		}
	}
}
.formCityPicker {
	flex: 1;
	overflow: hidden;
	position: relative;
}
.u-radio {
	float: none !important;
}
</style>
